import React from 'react';
import { generateImage } from '../services/api';

interface BackgroundGeneratorProps {
  text: string;
  emotion: string;
  onImageGenerate: (image: string) => void;
  loading: boolean;
  setLoading: (loading: boolean) => void;
}

const BackgroundGenerator: React.FC<BackgroundGeneratorProps> = ({
  text,
  emotion,
  onImageGenerate,
  loading,
  setLoading
}) => {
  const handleGenerate = async () => {
    setLoading(true);
    try {
      // 调用后端图片生成API
      const result = await generateImage(text, emotion);

      if (result.success) {
        onImageGenerate(result.data.image_url);
      } else {
        throw new Error(result.error || '图片生成失败');
      }
    } catch (error: any) {
      console.error('图片生成失败:', error);
      alert(`图片生成失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="mt-6 p-4 bg-gray-50 rounded-lg">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">情绪分析结果</h2>
          <p className="text-gray-600 mt-1">
            你输入的文字表达的情绪是: <span className="font-semibold text-indigo-600">{emotion}</span>
          </p>
        </div>
        <button
          onClick={handleGenerate}
          disabled={loading}
          className={`px-6 py-2 rounded-md ${
            loading
              ? 'bg-gray-400 cursor-not-allowed'
              : 'bg-green-600 text-white hover:bg-green-700 transition'
          }`}
        >
          {loading ? '生成中...' : '生成背景图片'}
        </button>
      </div>
    </div>
  );
};

export default BackgroundGenerator;